package com.hshh.controller;

import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.servlet.ModelAndView;

import com.hshh.common.Constant;
import com.hshh.domain.UserInfoSession;
import com.hshh.service.LoginService;
import com.hshh.util.CommonCommand;

@Controller
public class LoginController {
	@Autowired
	LoginService loginService;

	@RequestMapping(value={"/index.do"})
	public String login(HttpServletRequest request){
		String mav = "login";
		CommonCommand cc = new CommonCommand();
		if(cc.getSessionAuth(request)){
			mav = "main"+Constant.TILES;
		}
		return mav;
	}

	@RequestMapping(value={"/auth.json"})
	public ModelAndView auth(HttpServletRequest request) {
		CommonCommand cc = new CommonCommand();
		ModelAndView mav = new ModelAndView();
		Map<String, Object> param = cc.requestToMap(request);
		Map<String, Object> serviceResult = loginService.getAuth(param);

		if(Boolean.parseBoolean(serviceResult.get("result").toString())){
			UserInfoSession session = new UserInfoSession();
			if(serviceResult.containsKey("user_id")){
				session.setUser_id(serviceResult.get("user_id").toString());
			}
			if(serviceResult.containsKey("user_name")){
				session.setUser_name(serviceResult.get("user_name").toString());
			}
			if(serviceResult.containsKey("user_role")){
				session.setUser_role(serviceResult.get("user_role").toString());
			}
			if(serviceResult.containsKey("user_state")){
				session.setUser_state(serviceResult.get("user_state").toString());
			}
			request.getSession().setAttribute(Constant.SESSION_ID, session);
			Map<String, Object> result = new HashMap<String, Object>();
			result.put("result", serviceResult.get("result"));
			mav.addObject("result", result);
		}
		else{
			mav.addObject("result", serviceResult);
		}
		mav.setViewName(Constant.URL_JSONVIEW);
		return mav;
	}

	/**
	 * 로그인 화면으로 들어간다
	 * @return 로그인 페이지
	 */
    @RequestMapping(value="logout")
	public String logout( HttpSession session, Model model) {
//        Map<String, Object> result = new LinkedHashMap<String, Object>();
        session.invalidate();
        model.addAttribute(Constant.CODE_KEY, 0);
    	return Constant.URL_JSONVIEW;
	}
}
